//
//  UICollectionResueView.swift
//  live
//
//  Created by melvyn on 2018/8/17.
//  Copyright © 2018 NEET. All rights reserved.
//

import Foundation
import ObjectiveC.runtime
import RxSwift
import RxCocoa

extension Reactive where Base: UICollectionReusableView {
    public var prepareForReuse: Observable<Void> {
        return Observable.of(
            base.rx.sentMessage(#selector(UICollectionReusableView.prepareForReuse)).map { _ in () },
            base.rx.deallocated
            )
            .merge()
    }
    
    public var disposeBag: DisposeBag {
        MainScheduler.ensureExecutingOnScheduler()
        var key = "Rx.ReusableView_disposeBag_associatedKey"
        if let bag = objc_getAssociatedObject(base, &key) as? DisposeBag {
            return bag
        }
        
        let bag = DisposeBag()
        objc_setAssociatedObject(base, &key, bag, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        
        _ = base.rx.sentMessage(#selector(UICollectionReusableView.prepareForReuse))
            .subscribe(onNext: { _ in
                let newBag = DisposeBag()
                objc_setAssociatedObject(self.base, &key, newBag, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            })
        
        return bag
    }
}

extension Reactive where Base: UITableViewCell {
    public var prepareForReuse: Observable<Void> {
        return Observable.of(
            base.rx.sentMessage(#selector(UITableViewCell.prepareForReuse)).map { _ in () },
            base.rx.deallocated
            )
            .merge()
    }
    
    public var disposeBag: DisposeBag {
        MainScheduler.ensureExecutingOnScheduler()
        
        var key = "Rx.ReusableView_disposeBag_associatedKey"
        if let bag = objc_getAssociatedObject(base, &key) as? DisposeBag {
            return bag
        }
        
        let bag = DisposeBag()
        objc_setAssociatedObject(base, &key, bag, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        
        _ = base.rx.sentMessage(#selector(UITableViewCell.prepareForReuse))
            .subscribe(onNext: { _ in
                let newBag = DisposeBag()
                objc_setAssociatedObject(self.base, &key, newBag, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            })
        
        return bag
    }
}
